package org.foreveross.que.infra.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.foreveross.que.entity.TopicEntity;
import org.foreveross.que.infra.TopicRepository;
import org.foreveross.que.infra.base.ddd.repository.EntityHibernateRepository;
import org.springframework.stereotype.Repository;

@Repository
public class TopicRepositoryImpl extends EntityHibernateRepository implements TopicRepository {

	private static final String alias = "t";
	private static final String FIND_SUBJECT_SQL =
	"from TopicEntity t where t.state = 1 and 1=1 ";
	
	private static final String FIND_SUBJECT_COUNT_SQL
	= "select count(t) from TopicEntity t where t.state = 1 and 1=1 ";
	
	
	/**
	 * 根据条件分页查询记录
	 * @param params
	 * @param pageIndex
	 * @param pageLen
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("static-access")
	@Override
	public List<TopicEntity> findSubjects(Map <String ,Object> paramsMap, Integer pageIndex,Integer pageLen) throws Exception {
		String queryStr = FIND_SUBJECT_SQL;
		Object [] arr = this.generateHqlByConditions(paramsMap, alias);
		queryStr += arr[0].toString();
		Object searchType = paramsMap.get("searchType");
		queryStr += " order by t.isStickie desc";
		if(searchType!=null){
		if(StringUtils.equals("one", searchType.toString())){
			queryStr += " , " + this.alias + ".lastTime desc" ;
		}else if(StringUtils.equals("two", searchType.toString())){
			queryStr += " , " + this.alias + ".replyCount desc" ;
		}else if(StringUtils.equals("four", searchType.toString())){
			queryStr += " , " + this.alias + ".createTime desc" ;
		}
		}
		Object [] params = (Object [])arr[1];
		return super.queryResult(queryStr, params, pageIndex, pageLen);
	}
	/**
	 * 根据条件查询记录总数
	 * @param params
	 * @return
	 * @throws Exception
	 */	
	@Override
	public Long findSubjectsCount(Map <String ,Object> paramsMap) throws Exception {
		String queryStr = FIND_SUBJECT_COUNT_SQL;
		Object [] arr = this.generateHqlByConditions(paramsMap, alias);
		queryStr += arr[0].toString();
		Object [] params = (Object [])arr[1];
		return super.queryResultSize(queryStr, params);
	}
	
	private Object[] generateHqlByConditions(Map <String ,Object> paramsMap,String alias){
		Object[] finalResult=new Object[2];
		StringBuffer queryStr =  new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		if(paramsMap != null && paramsMap.size()!=0){
			for(String key : paramsMap.keySet()){
				Object value = paramsMap.get(key);
				if(value==null){
					continue;
				}
				if("searchType".equals(key)){
					continue;//该属性应该后面在处理
				}
				
				if("mid".equals(key)&&value instanceof List){
					List<String> availMenus = (List<String>)value;
					queryStr.append(" and ").append(alias).append(".").append(key);
					queryStr.append(" in (");
					for(int i =0;i<availMenus.size();i++){
						if(i<availMenus.size()-1){
						queryStr.append("?,");
						}else{
							queryStr.append("?)");
						}
						params.add(availMenus.get(i));
					}
					continue;
				}else if("title".equals(key)){
					if(StringUtils.isNotBlank(value.toString())){
						queryStr.append(" and ").append(alias).append(".").append(key);
						queryStr.append(" like ?");
						value = "%"+StringUtils.trim(value.toString())+"%";
					}else{
						continue;
					}
				}else if(value instanceof Integer){
					if((Integer)value==0){
						continue;
					}else{
						queryStr.append(" and ").append(alias).append(".").append(key);
						queryStr.append("=?");
					}
				}else{
					if(value instanceof String){
						if(StringUtils.isBlank(value.toString())){
						continue;
						}else{
							value = StringUtils.trim((String)value);
						}
					}
					queryStr.append(" and ").append(alias).append(".").append(key);
					queryStr.append("=?");
				}
				params.add(value);
			}
		}
		finalResult[0] = queryStr;
		finalResult[1] = params.toArray();
		return finalResult;
	}
	
	public List search(final String searchString) {
		final String[] fields = new String[]{"name", "lyrics"}; // search on these fields

				List results = new ArrayList(); 
//				try {
//					FullTextEntityManager fullTextEntityManager =Search.getFullTextEntityManager(super.entityManager);
//					MultiFieldQueryParser parser = new 
//					parser.setDefaultOperator(QueryParser.AND_OPERATOR); // overrides the default OR_OPERATOR, so that all words in the search are required
//					org.apache.lucene.search.Query query = parser.parse(searchString);
//					Query fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Song.class);
//					results = fullTextQuery.getResultList();
//				}
//				catch (Exception e) {
////					throw new PersistenceException(e);
//				}
				return results; 
//			}
//		});
	}
	
//	private String getSqlBySearchType(StringBuffer queryStr,String searchType){
//		
//	}
}
